using Core.SimpleTemp.Application;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Core.SimpleTemp.Repositories.Internal;
using Core.SimpleTemp.Application.UserApp;
using Core.SimpleTemp.Entitys;
using Spire.Pdf.Exporting.XPS.Schema;
using Microsoft.AspNetCore.Http;

namespace Core.SimpleTemp.Api.ZB
{
    /// <summary>
    /// ZB_SafetyUser
    ///</summary>
    [ApiExplorerSettings(GroupName = "Sys")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    [Authorize]//验证是否登录
    public class ZB_SafetyUserController : CoreApiController
    {
        private readonly CoreDBContext _coreDBContext;
        private readonly ZB_SafetyUserService _service;
        private readonly ZB_OfficeSafetyService _Offiecservice;
        private readonly SysUserAppService _Userservice;
        /// <summary>
        /// ZB_SafetyUser
        ///</summary>
        public ZB_SafetyUserController(ZB_SafetyUserService service, ZB_OfficeSafetyService Offiecservice,CoreDBContext coreDBContext,
            SysUserAppService Userservice)
        {
            _Offiecservice = Offiecservice;
            _service = service;
            _Userservice = Userservice;
            _coreDBContext = coreDBContext;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        [PermissionFilter(nameof(ZB_SafetyUserController) + "_" + nameof(ZB_SafetyUserController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult>
            GetList(PagingModel<ZB_SafetyUserDto>
                pagingQueryModel)
        {
            IPageModel<ZB_SafetyUserDto>
                result;
            result = await _service.GetList(pagingQueryModel);

            //List<ZB_SafetyUserDto> List = new List<ZB_SafetyUserDto>();
            //for (int i = 0; i < result.PageData.Count; i++)
            //{
            //    List.Add(result.PageData[i]);
            //}

            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList1")]
        [PermissionFilter(nameof(ZB_SafetyUserController) + "_" + nameof(ZB_SafetyUserController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult>
            GetList1(PagingModel<ZB_SafetyUserDto>
                pagingQueryModel)
        {
            IPageModel<ZB_SafetyUserDto>
                result;
            result = await _service.GetList(pagingQueryModel);

            result.PageData.ForEach(dto =>
            {
                decimal Scope = 0;
                dto.ZB_OfficeSafety.ToList().ForEach(a =>
                {
                    Scope += Convert.ToDecimal(a.scope);
                    var itemType = a.itemType;
                    var ItemName = _coreDBContext.ZB_ProjectTypes.Where(x => x.Id == itemType).FirstOrDefault()?.itemType;
                    a.Mark01 = ItemName;
                });
                dto.Mark04 = (Convert.ToInt32(Scope)).ToString();

            });

            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>
        [HttpPost("GetUserList")]
        [PermissionFilter(nameof(ZB_SafetyUserController) + "_" + nameof(ZB_SafetyUserController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult> GetUserList(PagingModel<SysUserDto> pagingQueryModel)
        {

            var FactoryId = _coreDBContext.SysFactory.Where(x => x.FactoryName == "总部").FirstOrDefault().Id;
            IPageModel<SysUserDto> result = null;
            result = await _Userservice.GetList(pagingQueryModel);
            result.PageData = result.PageData.Where(x => x.SysUserInfor.WorkCompany== FactoryId).ToList();

            //var PersonList = _coreDBContext.SysUserInfor.Where(x => x.WorkCompany == FactoryId).ToList();
            //List<SysUserDto> User = new List<SysUserDto>();
            //for (int i = 0; i < result.PageData.Count; i++)
            //{
            //    if (result.PageData[i].Name != "" && result.PageData[i].Name != null)
            //    {
            //        User.Add(result.PageData[i]);
            //    }
            //}
            //result.PageData = User;
          //  result.RowCount = User.Count;
           // result.count = User.Count;
            return this.JsonSuccess(result);
        }



        /// <summary>
        /// </summary>
        /// <returns></returns>
        [HttpGet("BasisType")]
        public async Task<IActionResult> BasisType()
        {
            var result = await _service.GetBasisType();
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(ZB_SafetyUserController) + "_" + nameof(ZB_SafetyUserController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult>
            SaveAsync(ZB_SafetyUserDto dto)
        {
            dto.CreateFactory = UserIdentity.Factory;
            //添加
            if (Equals(dto.Id, Guid.Empty))
            {
                var CheckName = _coreDBContext.ZB_SafetyUser.Where(x => x.Name == dto.Name && x.IsDeleted==false).ToList();
                if(CheckName.Count>0)
                {
                    return this.JsonFaild("添加用户姓名已存在！" );
                }
                dto.IsDeleted = false;
                await _service.InsertAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
            else
            {
                var Name = _coreDBContext.ZB_SafetyUser.Where(x => x.Id == dto.Id).FirstOrDefault().Name;
                if(Name !=dto.Name)
                {
                    var CheckName = _coreDBContext.ZB_SafetyUser.Where(x => x.Name == dto.Name && x.IsDeleted == false).ToList();
                    if (CheckName.Count > 0)
                    {
                        return this.JsonFaild("您要修改用户姓名已存在！");
                    }
                }

                await _service.UpdateAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
        }

        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(ZB_SafetyUserController) + "_" + nameof(ZB_SafetyUserController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult>
            DeleteMutiAsync([FromBody]Guid[] ids)
        {
            List<Guid> newList = new List<Guid>();
            for (int i = 0; i < ids.Count(); i++)
            {
                if (_coreDBContext.ZB_SafetyUser.Where(x => x.Id == ids[i]).Where(b => b.IsDeleted == false).ToList().Count > 0)
                {
                    newList.Add(ids[i]);
                }
            }
          //  newList.Add(ids);
            await _service.DeleteBatchAsync(newList.ToArray());
            return this.JsonSuccess();
        }
        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMutiAll")]
        [PermissionFilter(nameof(ZB_SafetyUserController) + "_" + nameof(ZB_SafetyUserController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult>
            DeleteMutiAllAsync([FromBody]Guid[] ids)
        {
            List<Guid> newList = new List<Guid>();
            for (int i = 0; i < ids.Count(); i++)
            {
                if (_coreDBContext.ZB_SafetyUser.Where(x => x.Id == ids[i]).Where(b => b.IsDeleted == false).ToList().Count > 0)
                {
                    newList.Add(ids[i]);
                }
            }
            for (int  j= 0;  j< newList.Count; j++)
            {
                var OffieList = _coreDBContext.ZB_OfficeSafety.Where(x => x.Name == newList[j]).ToList();
                if(OffieList.Count>0)
                {
                    OffieList.ForEach(e => _coreDBContext.ZB_OfficeSafety.Remove(e));
                    await _coreDBContext.SaveChangesAsync();
                }
            }
            //  newList.Add(ids);
            await _service.DeleteBatchAsync(newList.ToArray());
            return this.JsonSuccess();
        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        public async Task<IActionResult>
            Get(Guid id)
        {
            var model = await _service.GetAsync(id);
            if (model == null) return this.JsonFaild("未找到对应数据:" + id);

            var retModel = new
            {
                model.Id,
                model.Name,
                model.ZBSafetyFrameWorkId,
                model.Department,
                model.PhoneNumber,
                model.ExtensionNumber,
                //model.Dateofaddition,
                //model.Conferencecontent,
                //model.AttachmentId,
                //model.AttachmentName,
            };
            //  附件
            //var attachmentList = await _coreDBContext.SysFile.Where(a => a.B_ID == id).Select(a => "/api/File/DownLoad?id=" + a.Id).ToListAsync();

            return this.JsonSuccess(retModel);
        }


        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(ZB_SafetyUserController) + "_" + nameof(ZB_SafetyUserController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult>
            Export(PagingModel<ZB_SafetyUserDto>
                pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="data"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("Import")]
        //[PermissionFilter(nameof(FX_EquipmentFacilitiesController) + "_" + "导入")]
        public async Task<IActionResult> ImportAsync([FromForm]String data, [FromForm]List<IFormFile> file)
        {
            var retMeg = await _service.ImportAsync(file[0], data);
            if (!retMeg.Any())
            {
                return this.JsonSuccess();
            }
            else
            {
                return this.JsonFaild(retMeg[0].ToString());
            }
        }
        #endregion


    }
}
